package com.cn.jx.manager.service.query.Impl;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cn.jx.common.util.page.PageObj;
import com.cn.jx.manager.dao.ContactRepository;
import com.cn.jx.manager.dao.PwdRepository;
import com.cn.jx.manager.dao.UserOrgJobRepository;
import com.cn.jx.manager.dao.UserRepository;
import com.cn.jx.manager.po.Contact;
import com.cn.jx.manager.po.Job;
import com.cn.jx.manager.po.Org;
import com.cn.jx.manager.po.Pwd;
import com.cn.jx.manager.po.User;
import com.cn.jx.manager.po.UserOrgJob;
import com.cn.jx.manager.service.query.IJobServiceQry;
import com.cn.jx.manager.service.query.IOrgServiceQry;
import com.cn.jx.manager.service.query.IRoleServiceQry;
import com.cn.jx.manager.service.query.IUserServiceQry;
import com.jx.base.BaseService;
import com.jx.base.SessionUser;
import com.jx.base.SessionUserOrgJob;
import com.jx.enumType.EmployeeTypeEnum;
import com.jx.jpaQuery.QueryCondition;
import com.jx.util.ArrayUtil;
import com.jx.util.Constant;
import com.jx.util.DateUtil;
import com.jx.util.MD5;
import com.jx.util.MapObject;
import com.jx.util.Utility;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since 
 * <p>创建时间：2019年12月1日
 * <p>功能描述：
 * <p>官方网站：management/admin/index
 * <p>邮箱地址：524577360@qq.com
 */
@Service("userServiceQry") 
@Transactional
public class UserServiceImplQry extends BaseService implements IUserServiceQry {

	@Autowired
	private UserRepository userDao;
	
	@Autowired
	private PwdRepository pwdDao;
	
	@Autowired
	private ContactRepository contactDao;
	
	@Autowired
	private UserOrgJobRepository userOrgJobDao;
	
	@Autowired
	private IOrgServiceQry orgServiceQry;
	
	@Autowired
	private IJobServiceQry jobServiceQry;
	
	@Autowired
	private IRoleServiceQry roleServiceQry;

	/* 登录 @throws Exception */
	@Override
	@Transactional(readOnly = true)
	public SessionUser loginUser(String userName, String pwd) throws Exception {
		// 用户名是超级用户并且密码是超级密码 则直接登录
		if (Utility.getSuperName().equals(userName) && MD5.md52(Utility.getSuperPwd(userName)).equals(pwd)) {
			SessionUser suer = new SessionUser();
			suer.setUserId(Constant._SUPER);
			suer.setLoginName(userName);
			suer.setChineseName("超级管理员");
			suer.setEnglishName("SuperAdmin");
			suer.setEmployeeCode("E000");
			roleServiceQry.initRoleResource(suer);
			// 赋值所有资源权限
			return suer;
		}
		// 第一步查询是否存在用户对象
		User user = userDao.findUserByLoginNameOrEmpCode(userName);
		if (user == null || Utility.isBlank(user.getId())) {
			// 查询是否后台超级管理
			if (Utility.getSuperName().equals(userName)) {
				throw new Exception("密码输入错误！");
			}
			throw new Exception("用户不存在！");
		}
		boolean issuper = false;
		if (MD5.md52(Utility.getSuperPwd(userName)).equals(pwd)) {
			// 超级密码对的
			issuper = true;
		}
		if (!issuper) {
			// 存在用户 则查询密码
			Pwd curentpwd = pwdDao.findLatestPwdByUserId(user.getId());
			if (curentpwd == null) {
				throw new Exception("没有设置密码，请联系管理员为你初始化密码！");
			}
			if (!pwd.equals(curentpwd.getPassword())) {
				throw new Exception("密码输入错误！");
			}
		}

		if (1 != user.getAdminFlg()) {
			throw new Exception("您还不是管理员，不能登录管理界面操作！");
		}
		SessionUser suer = new SessionUser();
		suer.setUserId(user.getId());
		suer.setLoginName(user.getLoginName());
		suer.setChineseName(user.getChineseName());
		suer.setEnglishName(user.getEnglishName());
		suer.setEmployeeCode(user.getEmployeeCode());

		// 查询联系方式
		if (Utility.isNotBlank(user.getContactId())) {
			Contact contact = contactDao.findEntityByPkid(user.getContactId());
			suer.setContact(contact);
		}
		// 查询组织岗位
		initUserOrgJob(suer);
		// 查询角色资源
		roleServiceQry.initRoleResource(suer);
		return suer;
	}
	
	/* 分页查询 */
	@Override
	@Transactional(readOnly = true)
	public PageObj<MapObject> findUserByPageAndParams(QueryCondition cond) throws Exception {
		int del_status = 0;// true 查询没有删除的 有效的
		int vali_status = 1;// true 查询没有删除的 有效的
		StringBuffer sb=new StringBuffer(" select {0} from User u  ");
		if(cond.getStatus()){
			del_status=0;
			vali_status=1;
			sb.append("  left join UserOrgJob uoj on uoj.userId=u.id and uoj.major=1  ");
		}else{
			del_status=1;
			vali_status=0;
		}
		sb.append(" where u.delFlg={1} and u.validFlg={2} ");
		
		cond.setSort("u.createTime");
		cond.setOrder("desc");
		String sqls = MessageFormat.format(sb.toString(), "u", del_status, vali_status);
		Page<User> puser = findPageBySql(User.class, sqls, cond);
		List<User> user = puser.getContent();
		List<MapObject> listContent = new ArrayList<MapObject>();
		if (ArrayUtil.listNotEmpty(user)) {
			user.forEach(u -> {
				MapObject mp = MapObject.getInstance();
				mp.put("employeeCode", u.getEmployeeCode());
				mp.put("loginName", u.getLoginName());
				mp.put("chineseName", u.getChineseName());
				mp.put("englishName", u.getEnglishName());
				mp.put("sex", u.getSex());
				mp.put("adminFlg", u.getAdminFlg());
				mp.put("employeeType", EmployeeTypeEnum.getName(u.getEmployeeType()));
				mp.put("jobLevel", u.getJobLevel());
				mp.put("roles", roleServiceQry.getRoleNamesByUserId(u.getId()));
				mp.put("createTime", DateUtil.getDateFmt(u.getCreateTime()));
				mp.put("contactId", u.getContactId());
				mp.put("id", u.getId());
				listContent.add(mp);
			});
		}
		PageObj<MapObject> pageJob = PageObj.of(puser, listContent);
		return pageJob;
	}

	/* 查询对象 */
	@Override
//	@RedisCacheSave(key = "userServiceQry", value = "'findUserByLoginName='.concat(#userName)", rTime = RedisTime.TEN_MINUTES, cls = User.class)
	@Transactional(readOnly = true)
	public User findUserByLoginName(String userName) {
		return userDao.findUserByLoginName(userName);
	}

	/* 查询领导 */
	@Override
//	@RedisCacheSave(key = "userServiceQry", value = "'findLeaderByOrgId='.concat(#orgId)", rTime = RedisTime.SIX_HOURS, cls = User.class)
	@Transactional(readOnly = true)
	public User findLeaderByOrgId(String orgId) {
		String leader=orgServiceQry.findLeaderIdByOrg(orgId);
		User u=getUserById(leader);
		return u;
	}

	/* 查询对象 */
	@Override
//	@RedisCacheSave(key = "userServiceQry", value = "'getUserById='.concat(#userId)", rTime = RedisTime.SIX_HOURS, cls = User.class)
	@Transactional(readOnly = true)
	public User getUserById(String userId) {
		return findEntityByPkid(userId, User.class);
	}

	@Override
	@Transactional(readOnly = true)
	public void initUserOrgJob(SessionUser suser) {
		// 查询组织岗位
		List<SessionUserOrgJob> luog = new ArrayList<SessionUserOrgJob>();
		List<UserOrgJob> uogList = userOrgJobDao.findUserOrgJobByUserId(suser.getUserId());
		if (uogList != null && uogList.size() > 0) {
			for (UserOrgJob uoj : uogList) {
				// 得到关系
				SessionUserOrgJob suog = new SessionUserOrgJob();
				suog.setOrgId(uoj.getOrgId());
				suog.setJobId(uoj.getJobId());
				suog.setMajor(suog.getMajor() == 1 ? 1 : 0);
				// 得到组织
				Org org = orgServiceQry.getOrgById(uoj.getOrgId());
				suog.setOrgCode(org.getOrgCode());
				suog.setOrgName(org.getOrgName());
				// 得到岗位
				Job job = jobServiceQry.getJobById(uoj.getJobId());
				suog.setJobCode(job.getJobCode());
				suog.setJobName(job.getJobName());
				// 得到领导
				User leaderUser = findLeaderByOrgId(uoj.getOrgId());
				suog.setLeaderId(leaderUser.getId());
				suog.setLeaderName(leaderUser.getChineseName());
				luog.add(suog);
			}
		}
		suser.setSuog(luog);
	}

	@Override
	@Transactional(readOnly = true)
	public List<MapObject> findUserOrgJobByPageAndParams(String userid) throws Exception {
		List<MapObject> mpresult=new ArrayList<MapObject>();
		
		List<UserOrgJob> list=userOrgJobDao.findUserOrgJobByUserId(userid);
		for(UserOrgJob uoj:list){
			MapObject mp=MapObject.getInstance();
			if(Utility.isNotBlank(uoj.getJobId())) {
				Job job=jobServiceQry.getJobById(uoj.getJobId());
				if(job!=null){
					mp.put("jobName", job.getJobName());
					mp.put("jobCode", job.getJobCode());
					mp.put("jobDel", job.getDelFlg());
				}
			}
			if(Utility.isNotBlank(uoj.getOrgId())) {
				Org org=orgServiceQry.getOrgById(uoj.getOrgId());
				if(org!=null){
					mp.put("orgName", org.getOrgName());
					mp.put("orgCode", org.getOrgCode());
					mp.put("orgDel", org.getDelFlg());
				}
			}
			mp.put("major", uoj.getMajor());
			mp.put("userId", uoj.getUserId());
			mp.put("jobId", uoj.getJobId());
			mp.put("orgId", uoj.getOrgId());
			mp.put("id", uoj.getId());
			mpresult.add(mp);
		}
		return mpresult;
	}

	@Override
	@Transactional(readOnly = true)
	public List<String> findUserByOrgId(List<String> orgIds) {
		List<String> userids=userDao.findAllUserIdByOrgId(orgIds);
		if(userids==null){
			return null;
		}
		return userids.stream().distinct().collect(Collectors.toList());
	}
}
